/**
 * <pre>
   Copyright 2016 aaron.sd

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 * </pre>
 * 
 * @author aaronwong.sd@foxmail.com
 * @version 下午3:11:59
 */
package com.iwechat.mp.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwechat.config.CommConst;
import com.iwechat.mp.service.TemplateMessageHandler;
import com.iwechat.mp.service.WxmpApi;
import com.iwechat.util.StringUtil;

/**
 * 模板消息控制器
 * 
 * @author aaronwong.sd@foxmail.com
 */
@Controller
@RequestMapping("/mp/template")
public class TemplateMessageController {
    private static final Logger  LOG = LoggerFactory.getLogger(TemplateMessageController.class);
    private static final WxmpApi API = WxmpApi.getAPI();

    @Autowired
    WebApplicationContext        wac;

    @RequestMapping(value = "/message", method = RequestMethod.POST)
    public void sendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取客户端上送消息
        InputStream in = request.getInputStream();
        String charset = request.getCharacterEncoding();
        String message = IOUtils.toString(in, charset);
        JSONObject req = JSON.parseObject(message);
        LOG.info("recive tm <<< " + req.toJSONString());
        // 消息id
        long seqnb = req.getLongValue(CommConst.SEQNB);
        req.remove(CommConst.SEQNB);
        JSONObject resp = API.templateMessageSend(req.toJSONString(), seqnb);
        resp.put(CommConst.SEQNB, seqnb);
        // 发送结果缓存到链表,等待批量处理
        TemplateMessageHandler tmh = wac.getBean(TemplateMessageHandler.class);
        tmh.addResponse(resp);

        // 发送响应
        try {
            response.setCharacterEncoding(request.getCharacterEncoding());
            response.setContentType("text/json;charset=" + response.getCharacterEncoding());
            PrintWriter write = response.getWriter();
            write.println(resp.toJSONString());
            LOG.info("send response >>> " + resp.toJSONString());
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    @RequestMapping(value = "/monitor/resp", method = RequestMethod.GET)
    public void monitor(HttpServletRequest request, HttpServletResponse response) {
        TemplateMessageHandler tmh = wac.getBean(TemplateMessageHandler.class);
        // 发送响应
        try {
            response.setCharacterEncoding(response.getCharacterEncoding());
            response.setContentType("text/html;charset=" + response.getCharacterEncoding());
            PrintWriter write = response.getWriter();
            write.println(StringUtil.toHtml(tmh.monitorResp()));
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
